<%@ page import="com.example.softwareconfigurationcoursedesign.ShopPage.Product" %>
<%@ page import="java.util.List" %>
<%@ page import="java.sql.DriverManager" %>
<%@ page import="java.sql.Connection" %>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
    <title>搜索结果</title>
    <link rel="stylesheet" href="CSS/SearchResultOfShopping.css">
</head>
<body>
<h1><button onclick="window.location.href='shop.jsp'">< 点击返回</button>  <br>搜索结果</h1>
<div class="product-container">
    <%
        List<Product> searchResults = (List<Product>) request.getAttribute("productList");
        if (searchResults != null) {
            int count = 0;
            for (Product product : searchResults) {
    %>
    <div class="product-item">
        <!-- 产品信息展示 -->
        <div><img src="<%= product.getPurl() %>" alt="<%= product.getPname() %>"></div>
        <div>产品名称: <%  String name=null;
            String productName = product.getPname();
            if (productName.length() > 25) {
               name = productName.substring(0, 23) + "...";
            } %> <%=name%>
        </div>
        <div>价格: <%= product.getPprice() %>
        </div>

        <div style="text-align: center">
            <button onclick="addToCart('<%= product.getPname() %>')">加入购物车</button>
        </div>
    </div>
    <%
        count++;
        // 每行显示5个产品
        if (count % 5 == 0) {
    %>
</div>
<div class="product-container">
    <%
                }
            }
        }
    %>
</div>
<script>
    function openEditProductWindow() {
        window.open("editProduct.jsp", "_blank", "width=400,height=300");
    }

    function addToCart(name) {
        window.alert('商品:' + name + '已经加入购物车\n期待您的购买');
        let cart = [];
        if (document.cookie.includes('cart=')) {
            const cookies = document.cookie.split(';');
            for (let i = 0; i < cookies.length; i++) {
                const cookie = cookies[i].trim();
                if (cookie.startsWith('cart=')) {
                    const cartJSON = decodeURIComponent(cookie.substring(5));
                    cart = JSON.parse(cartJSON);
                    break;
                }
            }
        }
        cart.push(name);
        const cartJSON1 = JSON.stringify(cart);
        document.cookie = 'cart=' + encodeURIComponent(cartJSON1) + '; expires=Thu, 01 Jan 2024 00:00:00 UTC; path=/;';

        // 触发自定义事件，通知其他组件购物车有变化
        const event = new CustomEvent('CartMessage', {
            detail: {
                type: 'CartButtonClick',
                data: {
                    name: name,
                    cart: cart
                }
            }
        });
        window.dispatchEvent(event);
    }
</script>
</body>
</html>